package org.niit.dao

import org.niit.util.JDBCUtil

// 对数据库做操作的代码
class BlackListDao {
  // 判断当前用户是否在黑名单表中
  def selectBlackUserById(userId: String): Boolean = {
    //1.获得MySQL连接
    val conn = JDBCUtil.getConnection
    //2.编写并执行SQL语句，以及传递参数

    val bool = JDBCUtil.isExist(conn,
      "select * from black_list where userid = ?",
      Array(userId))

    //3.关闭连接
    conn.close()

    bool

  }

  // 向黑名单中添加数据，如果该数据存在，就更新id
  def insertBlackList(userId: String): Unit = {

    val conn = JDBCUtil.getConnection
    //2.编写SQL 以及传递参数
    JDBCUtil.executeUpdate(conn,
      "insert into black_list(userid) values (?) on duplicate key update userid = ? ", // 索引对应的记录不存在时插入，存在可更新字段时更新，否则不做操作
      Array(userId, userId) // 上面的问号占位符所对应的参数
    )
    conn.close()
  }

  // 向每日用户点击广告次数表中添加数据
  def insertUserAdCount(day: String, userId: String, adId: String, count: Int): Unit = {
    val conn = JDBCUtil.getConnection
    JDBCUtil.executeUpdate(conn,
      "insert into user_ad_count(dt,userid,adid,count) values (?,?,?,?) on duplicate key update count = count + ? ",
      Array(day, userId, adId, count, count)
    )
    conn.close()
  }

  // 查看用户点击广告次数
  def checkUserByCount(day: String, userId: String, adId: String, count: Int): Boolean = {
    val conn = JDBCUtil.getConnection

    val bool = JDBCUtil.isExist(conn,
      "select * from user_ad_count where dt = ? and userid = ? and adid = ? and count >= ? ",
      Array(day, userId, adId, count)
    )
    conn.close()
    bool

  }

}
